package com.cupk.services;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cupk.entities.User;
import com.cupk.mapper.UserMapper; // 1. 【修改】: 导入 UserMapper
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper; // 2. 【修改】: 注入 UserMapper

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 3. 【修改】: 使用 QueryWrapper 和 userMapper.selectOne() 来查找用户
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));

        // 4. 【修改】: selectOne 在找不到时返回 null，所以我们需要手动检查 null
        if (user == null) {
            throw new UsernameNotFoundException("未找到用户名为 '" + username + "' 的用户");
        }

        // --- 后续的权限转换和返回逻辑保持不变，因为它们是正确的 ---

        // 确保这里从数据库取出角色 (已经是大写的 ADMIN 或 RESEARCHER) 后，加上 "ROLE_" 前缀
        List<GrantedAuthority> authorities = Collections.singletonList(
                new SimpleGrantedAuthority("ROLE_" + user.getRole())
        );

        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                authorities
        );
    }
}